import { NextRequest, NextResponse } from 'next/server';
import { parameterMappingDAO, entityDAO, classificationDAO } from '@/lib/database';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const specialty = searchParams.get('specialty');
    const tableType = searchParams.get('tableType') as 'naming' | 'location' | 'basic';
    const entityId = searchParams.get('entityId');
    
    if (!tableType) {
      return NextResponse.json(
        { error: '缺少必要参数: tableType' },
        { status: 400 }
      );
    }
    
    if (!['naming', 'location', 'basic'].includes(tableType)) {
      return NextResponse.json(
        { error: 'tableType 必须是 naming, location 或 basic' },
        { status: 400 }
      );
    }
    
    let mappings;
    let statistics;
    
    if (entityId) {
      // 查询特定实体对象的参数映射
      const entity = entityDAO.findById(parseInt(entityId));
      if (!entity) {
        return NextResponse.json(
          { error: '实体对象不存在' },
          { status: 404 }
        );
      }
      
      mappings = parameterMappingDAO.findByEntityAndType(parseInt(entityId), tableType as 'naming' | 'location' | 'basic');
      statistics = {
        totalEntities: 1,
        entitiesWithMappings: mappings.length > 0 ? 1 : 0,
        totalMappings: mappings.length,
        coverageRate: mappings.length > 0 ? '100' : '0'
      };
    } else if (specialty) {
      // 查询专业下所有实体对象的参数映射
      mappings = parameterMappingDAO.findBySpecialtyAndType(specialty, tableType as 'naming' | 'location' | 'basic');
      
      const entities = entityDAO.findBySpecialty(specialty);
      const totalEntities = entities.length;
      const entitiesWithMappings = new Set(mappings.map(m => m.entity_id)).size;
      
      statistics = {
        totalEntities,
        entitiesWithMappings,
        totalMappings: mappings.length,
        coverageRate: totalEntities > 0 ? ((entitiesWithMappings / totalEntities) * 100).toFixed(1) : '0'
      };
    } else {
      return NextResponse.json(
        { error: '必须提供 specialty 或 entityId 参数' },
        { status: 400 }
      );
    }
    
    // 获取所有分类标准用于参考
    const classifications = classificationDAO.findAll();
    
    return NextResponse.json({
      success: true,
      data: {
        specialty,
        tableType,
        entityId,
        mappings,
        statistics,
        classifications: classifications.slice(0, 100) // 限制返回数量
      }
    });
  } catch (error) {
    console.error('查询参数表失败:', error);
    return NextResponse.json(
      { 
        error: '查询参数表失败',
        details: error instanceof Error ? error.message : String(error)
      },
      { status: 500 }
    );
  }
} 